package br.gov.capgov.treinamento.ejb.sessionbeans;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import br.gov.capgov.treinamento.jpa.entidades.Sistema;
import br.gov.capgov.treinamento.jpa.entidades.Url;

@Stateless 
public class UrlEJB
{
	@PersistenceContext
	private EntityManager manager;
	 
	public List<Url> listaUrls()
	{
		Query query = manager.createQuery("FROM " + Url.class.getName() + " ORDER BY nome_url");
		List<Url> urls = query.getResultList();
		
		return urls;
	}
	
	public void insereUrl(Url url)
	{
		manager.persist(url);	
	}
		
	public void removeUrl(Integer id)
	{
		Url url = manager.find(Url.class, id);
		manager.remove(url);	
	}
	
	public Object carregaUrl(Class<?> classe, Object id)
	{	
		Object obj = new Object();

		try
		{
			obj = manager.find(classe, id);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			manager.getTransaction().rollback();	
		} 
		
		return obj;
	}
	public List<Url> procuraUrlsSistema(Integer id)
	{
		Query query = manager.createQuery("select u from "+ Url.class.getName() + " as u where sistema_id = "+ id + " ORDER BY nome_url");	
		List<Url> urls = query.getResultList();
		return urls;
	}
	
	public Url procuraUrl(Integer id)
	{
		return this.manager.find(Url.class, id) ;
	}
	
	public void atualizaUrl(Url url)
	{
		manager.merge(url);	
	}
	
	public Url buscaUrl(Url url)
	{
		Query query = manager.createQuery("FROM " + Url.class.getName() + " as u where nome_url = '"+ url.getNomeUrl() +"' ");
		
		try
		{
			Url nomeUrl = (Url) query.getSingleResult();
			return nomeUrl;
		}
		catch (NoResultException e)
		{
			return null;
		}
	}	
}